<template>
  <div class="add-task">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/main/dispatching/list' }">调度监控列表</el-breadcrumb-item>
      <el-breadcrumb-item>{{title}}</el-breadcrumb-item>
    </el-breadcrumb>
      <div class="body">
        <el-steps :active="activeIndex" align-center>
          <el-step title="填写调度信息" ></el-step>
          <el-step title="配置策略和计划" ></el-step>
        </el-steps>
        <div class="edit">
          <transition name="show">
            <div class="body-item" v-show="activeIndex === 1">
              <div class="task-all">
                <div class="task-left">
                  <div class="title" style="padding-left: 0">任务列表</div>
                  <taskList :disabled="disabled" @dragCall="dragCall"/>
                </div>
                <div class="task-right">
                  <div class="title" style="padding-bottom: 0">任务调度信息</div>
                  <el-form ref="form" :model="form" label-width="120px" :disabled="disabled">
                    <el-form-item label="任务调度名称:" prop="invokeName" :rules="{ required: true, message: '请输入任务名称', trigger: 'blur' }">
                      <el-input v-model="form.invokeName" size="mini" placeholder="请输入任务调度名称" :maxLength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" style="margin:20px 0" prop="remark">
                      <el-input type="textarea" :rows="3" v-model="form.remark" :maxLength="200" placeholder="请输入备注"></el-input>
                    </el-form-item>
                    <el-form-item label="关系图:">
                      <div class="echarts-item">
                        <jtopo v-if="isJtopo" :disabled="disabled" @clickNodeCall="clickNodeCall" @clearAllCall="clearAllCall" :node-list="form.nodeArr"/>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </transition>

          <transition>
            <div class="body-item" v-show="activeIndex === 2" style="padding-top: 15px;">
              <div class="edit-two">
                <div class="title">配置策略和计划</div>
                <el-form ref="form" :model="form" label-width="120px" :disabled="disabled">
                  <el-form-item label="标签:">
                    <div class="tab-bar">
                      <el-tag class="tag-item" v-for="(item,index) in form.tags" :key="index">{{item.tag}}</el-tag>
                      <el-button size="small" @click="isTag = true">标签管理</el-button>
                    </div>
                  </el-form-item>
                  <el-form-item label="任务失败策略:" :rules="{ required: true }">
                    <el-radio-group v-model="failedStrategy">
                      <el-radio :label="0">调度继续执行</el-radio>
                      <el-radio :label="1">调度停止执行</el-radio>
                      <el-radio :label="2">调度重新执行</el-radio>
                    </el-radio-group>
                    <span style="margin-left:10px;" v-if="failedStrategy === 2">
                      <el-input style="width:80px;" size="mini" :min="1" type="number" v-model="second"></el-input>&nbsp;秒后，调度重新执行
                    </span>
                  </el-form-item>
                  <el-form-item label="调度执行方式:" :rules="{ required: true }">
                    <el-radio-group v-model="form.concurrent">
                      <el-radio :label="0">串行执行</el-radio>
                      <el-radio :label="1">并发执行</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item>
                    <task-plan-set ref="plan" is-switch :execute-plan-data="executePlanData" :disabled="disabled"/>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </transition>
        </div>
      </div>

      <div slot="footer" class="footer">
        <el-button v-if="activeIndex === 1" type="primary" size="mini" @click="next">下一步</el-button>
        <el-button v-if="activeIndex === 2" type="primary" size="mini" @click="activeIndex = 1">上一步</el-button>
        <el-button v-if="activeIndex === 2 && !disabled" type="primary" size="mini" @click="addTask">保存</el-button>
      </div>

    <!--标签管理-->
    <tagManage :isTag="isTag" @useTags="useTags" @closeCall="closeCall"/>


  </div>
</template>
<script>
  import taskList from './TaskList'
  import tagManage from './TagManage'
  import TaskPlanSet from './TaskPlanSet'
  import Jtopo from "../../compoents/Jtopo"

  export default {
    name:'addTask',
    components:{
      taskList,
      tagManage,
      TaskPlanSet,
      Jtopo
    },
    data(){
      return {
        type: 0,
        detail: {},
        disable: false,
        activeIndex: 1,
        title: "",
        isJtopo: true,                    //刷新关系图组件
        form: {
          invokeName: "",                 //调度名称
          remark: "",                     //备注
          concurrent: 0,                  //执行方式、并、串行
          executePlanData: "",            //时间控件数据结构
          failedStrategy: 0,              //失败策略
          nodeArr: "",                    //关系图节点数据结构
          tags: [],                       //标签
          taskInvokeId: "",               //任务ID、修改时候用
          taskRelateInvokes: [],          //后端需要的关系图数据结构
          triggers: [],                   //后台需要的时间控件数据结构
        },
        isTag: false,
        failedStrategy: 0,
        second: 1,
        executePlanData: {},
      }
    },
    created() {
      console.log(this.$route.params);
      if (Object.keys(this.$route.params).length === 0) {
        return;
      }
      this.type = this.$route.params.type;
      this.detail = this.$route.params.detail;
      this.disabled = this.$route.params.disabled;

      //避免脏数据
      this.$store.commit("nodeList", []);
      switch (this.type) {
        case 0: this.title = "新增任务调度"; break;
        case 1: this.title = "修改任务调度"; break;
        default: this.title = "查看任务调度"; break;
      }
      if (Object.keys(this.detail).length > 0) {
        console.log("detail: ", this.detail);
        //填充数据
        this.form = this.detail;
        this.failedStrategy = Number(this.form.failedStrategy.split(",")[0]);
        this.second = this.form.failedStrategy.split(",").length > 1 ? Number(this.form.failedStrategy.split(",")[1]) : this.second;
        this.form.concurrent = this.form.concurrent ? 1 : 0;
        this.executePlanData = JSON.parse(this.detail.executePlanData) || {};
      }
    },
    beforeDestroy() {
      //清空缓存
      this.$store.commit("nodeList", []);
    },
    methods:{
      /**拖拽回调**/
      dragCall(row) {
        console.log("拖拽：", row);
        let data = JSON.parse(JSON.stringify(row));
        delete data.nodeArr;
        this.axios.get(this.baseApi.path+'/center/getUUID').then(res => {
          data.nodeId = res.data;
          data.taskDelay = 0; //延时默认为0
          this.$store.commit("interfaceNode", data);
        });
      },
      /**全部清空回调**/
      clearAllCall() {
        this.$store.commit("nodeList", []);
        this.form.nodeArr = "";
        this.isJtopo = false;
        this.$nextTick(() => {
          this.isJtopo = true;
        })
      },
      /**单击节点回调函数**/
      clickNodeCall(data) {
        //判断是查看就不做操作
        if (this.type > 1) {
          return;
        }
        this.$prompt('请输入延时', '输入提示', {
          inputValue: data.interfaceNode.taskDelay ? data.interfaceNode.taskDelay : "",
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^\d+$/,
          inputErrorMessage: '只能输入数字'
        }).then(({ value }) => {
          let nodeList = this.$store.getters.nodeList;
          for (let i = 0; i < nodeList.length; i++) {
            if (nodeList[i].elementType === "node" && nodeList[i].nodeId === data.nodeId) {
              nodeList[i].interfaceNode.taskDelay = value;
              break;
            }
          }
          this.$store.commit("nodeList", nodeList);
          //刷新数据
          this.isJtopo = false;
          this.form.nodeArr = JSON.stringify(this.getNodeList());
          this.$nextTick(() => {
            this.isJtopo = true;
          });
        })
      },
      /**下一步**/
      next() {
        console.log("this.$store.getters.nodeList: ", this.$store.getters.nodeList);
        if (this.activeIndex) {
          if (this.form.invokeName === "") {
            this.$message.error("任务调度名称");
            return;
          }
          if (this.getTaskRelateInvokes().length === 0) {
            this.$message.error("请添加节点");
            return;
          }
          this.activeIndex = 2;
        }
      },
      /**引用标签回调**/
      useTags(data) {
        this.form.tags = data;
        this.isTag = false
      },
      /**关闭标签窗口的回调**/
      closeCall() {
        this.isTag = false
      },
      /**获取组装前端需要还原的节点数据结构**/
      getNodeList() {
        let nodeList = [], nodeArr = [], vuexNodeList = this.$store.getters.nodeList;
        vuexNodeList.forEach(item => {
          if (item.elementType === "node") {
            nodeList.push(item);
          }
        });
        nodeList.forEach(item => {
          let parents = [], children = [];
          //查找父节点
          if (item.inLinks) {
            item.inLinks.forEach(out => {
              parents.push({
                interfaceNode: out.nodeA.interfaceNode
              });
            });
          }
          //查找子节点
          if (item.outLinks) {
            item.outLinks.forEach(out => {
              children.push({
                interfaceNode: out.nodeZ.interfaceNode
              });
            });
          }
          nodeArr.push({
            parents, children,
            nodeId: item.nodeId,
            interfaceNode: item.interfaceNode,
            x: item.x,
            y: item.y
          })
        });
        return nodeArr;
      },
      /**获取组装后端需要的数据结构**/
      getTaskRelateInvokes() {
        let nodeList = [], nodeArr = [], vuexNodeList = this.$store.getters.nodeList;
        //1.筛选node 对象
        vuexNodeList.forEach(item => {
          if (item.elementType === "node") {
            nodeList.push(item);
          }
        });
        nodeList.forEach(item => {
          let parentIds = [], childIds = [];
          //查找父节点
          if (item.inLinks) {
            item.inLinks.forEach(out => {
              parentIds.push(out.nodeA.interfaceNode.taskId);
            });
          }
          //查找子节点
          if (item.outLinks) {
            item.outLinks.forEach(out => {
              childIds.push(out.nodeZ.interfaceNode.taskId);
            });
          }
          nodeArr.push({
            parentIds, childIds,
            // nodeId: item.nodeId,
            taskId: item.interfaceNode.taskId,
            taskDelay: item.interfaceNode.taskDelay
          })
        });
        return nodeArr;
      },
      /**添加新任务**/
      addTask(){
        let planForm = this.$refs.plan.getExecutePlanData();
        if (planForm.loopTime.length === 0 && this.$refs.plan.executeChecked) {
          this.$message.error("请选择测试时间");
          return;
        }
        this.form.failedStrategy = this.failedStrategy === 2 ? this.failedStrategy + "," + this.second : this.failedStrategy + "";
        this.form.triggers = this.$refs.plan.executeChecked ? this.$refs.plan.createdData() : [];
        this.form.taskRelateInvokes = this.getTaskRelateInvokes();
        this.form.executePlanData = JSON.stringify(this.$refs.plan.getExecutePlanData());
        this.form.nodeArr = JSON.stringify(this.getNodeList());
        let params = this.form;
        params.concurrent = this.form.concurrent === 0;
        console.log(params.nodeArr);
        let url = "/taskInvoke/addTaskInvoke";
        if (params.taskInvokeId) {
          url = "/taskInvoke/updateTaskInvoke";
        }
        this.$http.post(url, params).then((res)=> {
          this.$store.commit("nodeList", []);
          this.$router.push({ name: "dispatching" })
        })
      }
    }
  }
</script>
<style lang="less" scoped>
    .body{
      .title{
        color: #333;
        font-weight: 600;
        padding-bottom: 15px;
        box-sizing: border-box;
      }
      .edit{
        overflow-y: auto;
        height: calc(100% - 58px);
      }
      &-item{
        height: 100%;
        .edit-two{
          width: 100%;
          border: 1px solid #e1e1e1;
          padding: 15px;
          margin: 0 auto;
          box-sizing: border-box;
        }
        .tab-bar{
          .tag-item{
            margin-right: 10px;
          }
        }
        .task-all{
          width: 100%;
          height: 100%;
          overflow: hidden;
          display: flex;
          padding-top: 15px;
          box-sizing: border-box;
          .task-left{
            position: relative;
            width: 400px;
            padding-right: 15px;
            border-right:8px solid #e1e1e1;
          }
          .task-right{
            width: calc(100% - 400px);
            height: 100%;
            padding-left: 15px;
            .echarts-item{
              height: 460px;
              width: 100%;
              border:1px solid #dcdfe6;
              border-radius: 4px;
              background: #eee;
            }
          }
        }
      }
    }
  .footer{
    text-align: center;
    padding: 15px 0;
    box-sizing: border-box;
  }
</style>
